//
//  TF_HorBackChatView.swift
//  TalkfunSDKDemo
//
//  Created by 邓盛明 on 2021/12/31.
//  Copyright © 2021 Talkfun. All rights reserved.
//

import UIKit

protocol TF_HorBackChatTableDelegate:class {
    func HorBackchat_clickToUrl(url:String)
}
class TF_HorBackChatView: UIView,UITableViewDelegate,UITableViewDataSource,TF_BackChatUrlDelegate {
    var datasource:[TF_BackChatLiveData] = []
    var tableview:UITableView!

    var scrollView:UIScrollView!
    var Tlayers:CAGradientLayer?
    weak var delegate: TF_HorBackChatTableDelegate?
    var tapGestueBlock:ZSTapGestureBlock?
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.scrollView = UIScrollView.init()
        self.scrollView.showsHorizontalScrollIndicator = false;
        self.scrollView.showsVerticalScrollIndicator = false;
        self.addSubview(self.scrollView)
         
        self.tableview = UITableView.init(frame: CGRect.zero)
        self.tableview.backgroundColor = UIColor.clear
        self.tableview.delegate = self;
        self.tableview.dataSource = self;
        self.tableview.separatorStyle = .none
        self.tableview.showsVerticalScrollIndicator = false
        self.tableview.showsHorizontalScrollIndicator = false
        self.tableview.register(TF_BackChatCell.self, forCellReuseIdentifier: "horbackChat")
    
        self.scrollView.addSubview(self.tableview)
      
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(tapClick))
        self.scrollView.addGestureRecognizer(tap)
    }
    
   @objc func tapClick()  {
       
       if (self.tapGestueBlock != nil) {
           self.tapGestueBlock?()
           
       }
       
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        self.scrollView.frame = self.bounds;
        self.scrollView.contentSize = CGSize(width: 0, height: self.bounds.size.height+10)
        self.scrollView.isScrollEnabled = false
        self.tableview.frame = self.scrollView.bounds;
        self.getLayers()
    }
    
    func getLayers() {
        if (self.Tlayers == nil) {
            let bgGradient = CAGradientLayer()
            bgGradient.colors = [UIColor(red: 1, green: 1, blue: 1, alpha: 0).cgColor, UIColor(red: 1, green: 1, blue: 1, alpha: 0.5).cgColor, UIColor(red: 1, green: 1, blue: 1, alpha: 1).cgColor]
            bgGradient.locations = [0, 0.08374399691820145, 1]
            bgGradient.frame = self.scrollView.bounds
            bgGradient.startPoint = CGPoint(x: 0.5, y: 0)
            bgGradient.endPoint = CGPoint(x: 0.5, y: 1)

            self.Tlayers = bgGradient;
            self.scrollView.layer.mask = bgGradient;
            
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.datasource.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let model:TF_BackChatLiveData = self.datasource[indexPath.row]
        
        return self.getHeight(model: model)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "horbackChat", for: indexPath) as! TF_BackChatCell
        cell.cellwidth = self.tableview.frame.size.width
        cell.backgroundColor = UIColor.clear
        cell.selectionStyle = .none

        cell.isOrientationLandscape = true
        let model:TF_BackChatLiveData = self.datasource[indexPath.row]
        cell.urldelegate = self
        cell.setBackmodel(model: model)
        cell.tag = indexPath.row
        cell.cellGestueBlock =  {  [weak self](img) in
            guard let `self` = self else {
                return
            }
            
            DispatchQueue.main.async {
                let model1:TF_BackChatLiveData = self.datasource[cell.tag]
                model1.image = img
                let index:IndexPath = IndexPath.init(item: cell.tag, section: 0)
                self.tableview.reloadRows(at: [index], with: .none)
            }
          
        }
    
        return cell
    }
    func upDateTableviewFrame() {
        var chatRecordH:CGFloat = self.frame.size.height
        var cellHeight:CGFloat = 0
        for i in 0..<self.datasource.count {
            let model:TF_BackChatLiveData = self.datasource[i]
            cellHeight = cellHeight + self.getHeight(model: model)
        }
        if cellHeight < chatRecordH {
            chatRecordH = cellHeight
            self.scrollView.isScrollEnabled = true
        } else {
            chatRecordH = self.frame.size.height;
            self.scrollView.isScrollEnabled = false
        }
        let chatRecordY:CGFloat = self.frame.size.height - chatRecordH
        self.tableview.frame = CGRect(x: 0, y: chatRecordY, width: self.scrollView.frame.size.width, height: chatRecordH)
          
//        self.tableViewReloadData()
    }
    
    func tableViewReloadData()  {
        
//       self.tableview.reloadData()
       let indexpath = NSIndexPath.init(row: self.datasource.count - 1, section: 0)
       self.tableview.scrollToRow(at: indexpath as IndexPath, at: .bottom, animated: true)
    }
   
    
    func getHeight(model:TF_BackChatLiveData) -> CGFloat {
        

         var roleStr:String = ""
              
         if (model.role == .roleSpadmin) {
                    roleStr = "老师";
        
                }
                //=============== 如果是助教说的话 =================
              else if (model.role == .roleAdmin)
                {
                    roleStr = "助教";

                }

        if (model.imageURL.count>0) { //
            model.msg = "";
        } else {
            model.msg = model.msg
        }
        let nickname = model.nickname + " "
        let str = nickname + model.msg
        
        let contentDict:[AnyHashable:Any]? = TalkfunSharedTools.assembleAttributeString(str, boundingSize: CGSize(width: self.tableview.frame.size.width-35-16-12-16, height: 2000), fontSize: 14, shadow: false) as! [AnyHashable : Any]
     
        let attr:NSAttributedString = contentDict?["attributeStr"] as! NSAttributedString
       
        let AttributedString = NSMutableAttributedString.init(attributedString: attr)
        
        let attr33: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),]
        AttributedString.addAttributes(attr33, range: NSRange(location: 0, length: attr.length))
        let attr34: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),]
        AttributedString.addAttributes(attr34, range: NSRange(location: 0, length: model.nickname.count))
      
        if roleStr.count > 0 {
    
            let attch = NSTextAttachment.init()
           
            attch.bounds = CGRect(x: 0, y: -3, width: 27, height: 15)
            let imageStr = NSAttributedString.init(attachment: attch)
            AttributedString.insert(imageStr, at: model.nickname.count+1)
            let Attri = NSAttributedString.init(string: " ")
            AttributedString.insert(Attri, at: model.nickname.count+2)
            let AttributeName: [NSAttributedString.Key : Any] = [.kern:5]
            AttributedString.addAttributes(AttributeName, range: NSRange(location: model.nickname.count+2, length: 1))

        }
        
        let font:UIFont? = UIFont.systemFont(ofSize: 14)
        let size = TalkfunSharedTools.sizeLabelToFit(AttributedString, width: self.tableview.frame.size.width-35-16-12-16, fontSize: font!)
    
        
        
        
      
        var imgHeight:CGFloat = 0;
        if (model.imageURL.count>0) {
            if (model.image != nil) {
                if (model.image.size.width == model.image.size.height) {
                    imgHeight = 68 + 8
                } else if (model.image.size.width > model.image.size.height) {
                    let proportion:CGFloat = model.image.size.width / 68
                    imgHeight = model.image.size.height / proportion + 8
                } else if (model.image.size.width < model.image.size.height){
                    imgHeight = 68+8
                }
            } else {
                imgHeight = 50
            }
        
      } else {
          imgHeight = 0;
      }
      
      return size.height+4+12+imgHeight;


    }
  
    
    func updatePlayBackChatData(model:TF_BackChatLiveData)  {
        
        self.datasource.append(model)
//        self.upDateTableviewFrame()
      
    }
   
    func upList(list:NSArray) {
        
    }
    
    
    func urlClick(url:String) {
        self.delegate?.HorBackchat_clickToUrl(url: url)
    }
    
    
    func nsRange(from range:Range<String.Index>) -> NSRange {
        return NSRange(range,in: String.init())
       }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
